//
//  DiscoverHouseholdListViewController.m
//  HJB
//
//  Created by jiezsoft.com on 14-10-10.
//  Copyright (c) 2014年 jiezsoft.com. All rights reserved.
//

#import "DiscoverHouseholdListViewController.h"
#import "HouseholdDetailViewController.h"
#import "UIViewExt.h"
#import "CycleScrollViews.h"
#import "HttpRequest.h"
#import "UIButton+WebCache.h"
#import "RDVTabBarController.h"
#import "MJRefresh.h"
@interface DiscoverHouseholdListViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
@property (strong, nonatomic) NSString *ImageUrlStr;
@property (strong, nonatomic) NSString*contentStr;
@property (strong, nonatomic) NSString*titleStr;

@end
@implementation DiscoverHouseholdListViewController

{
    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    NSMutableArray*fid;
    NSMutableArray*title;
    NSMutableArray*content;
    NSMutableArray*imageUrl;
    NSMutableArray*author;
    NSMutableArray*pubTime;
    NSMutableArray*collectCount;
    NSMutableArray*commentCount;
    NSMutableArray*LinkType;
    NSMutableArray*LinkCode;
    NSMutableArray*ImageUrl;
    int pageNumber;
    CycleScrollViews *mainScorllView;
    NSString *result;
    float lastContentOffset;
    NSString*TotalCount;
    UITableView *table;
}
@synthesize alt = alt;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"发现";
        
    }
    return self;
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    // 禁用 iOS7 返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.title = @"资讯";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    [[self rdv_tabBarController] setTabBarHidden:NO];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    self.navigationController.delegate = self;
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
}


- (void)viewDidLoad
{
    
    [super viewDidLoad];
    [self requestData];
    [self addFooter];
    
}
-(void)requestData{
    self.sat=nil;
    pageNumber=1;
    pubTime= [[NSMutableArray alloc] init];
    author= [[NSMutableArray alloc] init];
    imageUrl= [[NSMutableArray alloc] init];
    content= [[NSMutableArray alloc] init];
    title= [[NSMutableArray alloc] init];
    fid= [[NSMutableArray alloc] init];
    LinkType= [[NSMutableArray alloc] init];
    LinkCode= [[NSMutableArray alloc] init];
    ImageUrl= [[NSMutableArray alloc] init];
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];
    UIView*foot=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    foot.backgroundColor=[UIColor whiteColor];
    table.tableFooterView=foot;
    
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"1" forKey:@"pageIndex"];
    [param setValue:@"30" forKey:@"pageSize"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"/Discover/Household/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                for (NSDictionary* dicc in arrr )
                {

                    [author addObject:[dicc valueForKey:@"author"]];
                    [ImageUrl addObject:[dicc valueForKey:@"imageUrlFull"]];
                    [content addObject:[dicc valueForKey:@"content"]];
                    [fid addObject:[dicc valueForKey:@"fid"]];
                    [title addObject:[dicc valueForKey:@"title"]];
                 
                    NSString* string =  [dicc valueForKey:@"pubTime"];
                    NSLog(@"-------------%@",string);
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
                    NSDate *destDate= [dateFormatter dateFromString:string];
                    
                    NSTimeInterval  timeInterval = [destDate timeIntervalSinceNow];
                    timeInterval = -timeInterval;
                    

                    
                    long temp = 0;
                  
                    if (timeInterval < 60) {
                        result = [NSString stringWithFormat:@"刚刚"];
                    }
                    else if((temp = timeInterval/60) <60){
                        result = [NSString stringWithFormat:@"%ld分前",temp];
                    }
                    
                    else if((temp = temp/60) <24){
                        result = [NSString stringWithFormat:@"%ld小时前",temp];
                    }
                    
                    else if((temp = temp/24) <30){
                        result = [NSString stringWithFormat:@"%ld天前",temp];
                    }
                    
                    else if((temp = temp/30) <12){
                        result = [NSString stringWithFormat:@"%ld月前",temp];
                    }
                    else{
                        temp = temp/12;
                        result = [NSString stringWithFormat:@"%ld年前",temp];
                    }
                    
                    
                    [pubTime addObject:result];
                }
                if (arrr.count>0) {
                    [self _AutoScrollView];

                }
                if (arrr.count>1) {
                     [author removeObjectAtIndex:0];
                     [ImageUrl removeObjectAtIndex:0];
                     [content removeObjectAtIndex:0];
                     [fid removeObjectAtIndex:0];
                     [title removeObjectAtIndex:0];
                     [pubTime removeObjectAtIndex:0];
                    }[table reloadData];
                }else{
                [Global hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [Global showTextHudSub:requestResultStr view:self.view];
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];

}
//上拉刷新
- (void)addFooter
{
    
    MJRefreshFooterView* footer = [MJRefreshFooterView footer];
    footer.scrollView = table;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView* refreshView)
    {
        if (TotalCount.intValue/30>=pageNumber) {
            pageNumber++;
            NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
            NSString* tokenId = [user1 objectForKey:@"tokenId"];
            NSMutableDictionary *params = [NSMutableDictionary new];
            [params setValue:tokenId forKey:@"tokenId"];
            [params setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
            [params setValue:@"30" forKey:@"pageSize"];
            [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
            [HttpRequest requestData:@"/Discover/Household/List" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
//                    NSLog(@"====%@",severDataDict.dataDict);
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        NSMutableArray* arrr=[[NSMutableArray alloc]init];
                        arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                        for (NSDictionary* dicc in arrr )
                        {
                            
                            [author addObject:[dicc valueForKey:@"author"]];
                            [ImageUrl addObject:[dicc valueForKey:@"imageUrlFull"]];
                            [content addObject:[dicc valueForKey:@"content"]];
                            [fid addObject:[dicc valueForKey:@"fid"]];
                            [title addObject:[dicc valueForKey:@"title"]];
                            
                            NSString* string =  [dicc valueForKey:@"pubTime"];
                            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                            [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
                            NSDate *destDate= [dateFormatter dateFromString:string];
                            NSTimeInterval  timeInterval = [destDate timeIntervalSinceNow];
                            timeInterval = -timeInterval;
                            long temp = 0;
                            
                            if (timeInterval < 60) {
                                result = [NSString stringWithFormat:@"刚刚"];
                            }
                            else if((temp = timeInterval/60) <60){
                                result = [NSString stringWithFormat:@"%ld分前",temp];
                            }
                            
                            else if((temp = temp/60) <24){
                                result = [NSString stringWithFormat:@"%ld小时前",temp];
                            }
                            
                            else if((temp = temp/24) <30){
                                result = [NSString stringWithFormat:@"%ld天前",temp];
                            }
                            
                            else if((temp = temp/30) <12){
                                result = [NSString stringWithFormat:@"%ld月前",temp];
                            }
                            else{
                                temp = temp/12;
                                result = [NSString stringWithFormat:@"%ld年前",temp];
                            }
                            [pubTime addObject:result];
                            }[table reloadData];
                        }else{
                        NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                        [Global showTextHudSub:requestResultStr view:self.view];
                    }}
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    [Global showTextHudSub:@"连接失败" view:self.view];
                }
                
            }];
        }else{
            NSString *requestResultStr=@"没有更多数据了！";
            [Global showTextHudSub:requestResultStr view:self.view];
            }
        [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:2.0f];
        NSLog(@"%@--->正在刷新", refreshView.class);
    };
    
}
- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    [table reloadData];
    [refreshView endRefreshing];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [title count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIImageView*imageTitle=[[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 90, 70 )];
        [imageTitle.layer setCornerRadius:2.0];
        [imageTitle.layer setBorderWidth:0.3];
        [imageTitle.layer setMasksToBounds:YES];
        CGColorSpaceRef colorSpace2 = CGColorSpaceCreateDeviceRGB();
        CGColorRef colorref2 = CGColorCreate(colorSpace2,(CGFloat[]){ 0, 0, 0, 0.3 });
        [imageTitle.layer setBorderColor:colorref2];
        [imageTitle setImageWithURL:[NSURL URLWithString:[ImageUrl objectAtIndex:indexPath.row]]placeholderImage:[UIImage imageNamed:@""]];
        [cell.contentView addSubview:imageTitle];
        NSString *str = [NSString stringWithFormat:@"%@",  [title objectAtIndex:indexPath.row]];
        UIFont *font = [UIFont systemFontOfSize:15];
        CGSize size = CGSizeMake(320, 2000);
        CGSize labelsize = [str sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
        UILabel*titleLabel=[[UILabel alloc]initWithFrame:CGRectMake(imageTitle.right+10, 10, ScreenWidth-110,labelsize.height)];
        titleLabel.text =[NSString stringWithFormat:@"%@",  [title objectAtIndex:indexPath.row]];
        titleLabel.font=[UIFont systemFontOfSize:15];
        titleLabel.numberOfLines=0;
        [cell.contentView addSubview:titleLabel];
        UILabel*authorLabel=[[UILabel alloc]initWithFrame:CGRectMake(imageTitle.right+10, 60, ScreenWidth-110,11)];
        authorLabel.text =[NSString stringWithFormat:@"%@",  [author objectAtIndex:indexPath.row]];
        authorLabel.font=[UIFont systemFontOfSize:11];
        [cell.contentView addSubview:authorLabel];
        UILabel*timeLabel=[[UILabel alloc]initWithFrame:CGRectMake(ScreenWidth-110, 60, 95,12)];
        timeLabel.text =[NSString stringWithFormat:@"%@",  [pubTime objectAtIndex:indexPath.row]];
        timeLabel.textAlignment=NSTextAlignmentRight;
        timeLabel.font=[UIFont systemFontOfSize:12];
        [cell.contentView addSubview:timeLabel];
        
        if (title.count !=indexPath.row+1) {
            UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(15, 90-0.35, ScreenWidth-30, 0.35)];
            lineLabel1.backgroundColor=qianhuiColor;
            [cell.contentView addSubview:lineLabel1];
            
        }
        if (title.count ==indexPath.row+1) {
            UILabel *lineLabel1=[[UILabel alloc] initWithFrame:CGRectMake(0, 90-0.35, ScreenWidth, 0.35)];
            lineLabel1.backgroundColor=qianhuiColor;
            [cell.contentView addSubview:lineLabel1];
            
        }
        
        return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return  90;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    HouseholdDetailViewController *detailViewController = [[HouseholdDetailViewController alloc] init];
    detailViewController.ImageUrl=ImageUrl[indexPath.row];
    detailViewController.fid=fid[indexPath.row];
    detailViewController.titleStr=title[indexPath.row];
    detailViewController.content=content[indexPath.row];
    [self.navigationController pushViewController:detailViewController animated:YES];
   }
- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}
- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
//轮播视图
- (void )_AutoScrollView {
    self.ImageUrlStr=[ImageUrl objectAtIndex:0];
    self.contentStr=[content objectAtIndex:0];
    self.titleStr=[title objectAtIndex:0];
    UIButton* button=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 210)];
    [button setTitle:[fid objectAtIndex:0] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
    button.contentMode = UIViewContentModeScaleAspectFill;
    [button setImageWithURL:[NSURL URLWithString:[ImageUrl objectAtIndex:0]] placeholderImage:[UIImage imageNamed:@""]];
    [button  addTarget:self action:@selector(Btn:) forControlEvents:UIControlEventTouchUpInside];
    UILabel*titlelabel=[[UILabel alloc]initWithFrame:CGRectMake(0,350/2, ScreenWidth, 210-350/2)];
    titlelabel.text=[NSString stringWithFormat:@"  %@",[title objectAtIndex:0]];
    titlelabel.backgroundColor=[UIColor blackColor];
    titlelabel.alpha=0.5;
    titlelabel.font=[UIFont systemFontOfSize:16];
    [button addSubview:titlelabel];
    UILabel*label=[[UILabel alloc]initWithFrame:CGRectMake(0,350/2, ScreenWidth, 210-350/2)];
    label.text=[NSString stringWithFormat:@"  %@",[title objectAtIndex:0]];
    label.textColor=[UIColor whiteColor];
    label.font=[UIFont systemFontOfSize:16];
    [button addSubview:label];
    table. tableHeaderView=button;
}
-(void)Btn:(UIButton*)sender{
    HouseholdDetailViewController *detailViewController = [[HouseholdDetailViewController alloc] init];
    detailViewController.fid=sender.titleLabel.text;
    detailViewController.ImageUrl=self.ImageUrlStr;
    detailViewController.titleStr=self.titleStr;
    detailViewController.content=self.contentStr;
    [self.navigationController pushViewController:detailViewController animated:YES];
}
@end
